import 'package:grpc/grpc.dart' as grpc;
import 'package:grpc/grpc.dart';
import 'package:grpc_demo/src/generated/grpc_demo.pbgrpc.dart';

class SearchService extends SearchServiceBase {
  @override
  Future<SearchResponse> search(ServiceCall call, SearchRequest request) async {
    var result = <Result>[];
    for (var element in request.results) {
      if (element.title == "百度") {
        result.add(Result(url: "baidu.com"));
      } else {
        result.add(Result(url: "other.com"));
      }
    }
    return Future.value(SearchResponse(results: result));
  }

  @override
  Stream<SearchResponse> search1(
      ServiceCall call, SearchRequest request) async* {
    var list = [
      "baidu.com",
      "baidu.com1",
      "baidu.com2",
      "baidu.com3",
      "baidu.com4",
      "baidu.com5"
    ];
    for (var feature in list) {
      var result = <Result>[];
      Future.delayed(const Duration(seconds: 1));
      print("add value:$feature");
      result.add(Result(url: feature));
      yield SearchResponse(results: result);
    }
  }

  @override
  Future<SearchResponse> search2(
      ServiceCall call, Stream<SearchRequest> request) async {
    print(" search2");
    var result = <Result>[];
    await for (var element in request) {
      print(" element:$element");
    }
    // result.add(Result(url: "ssssss"));
    return Future.value(SearchResponse(results: result));
  }

  @override
  Stream<SearchResponse> search3(
      ServiceCall call, Stream<SearchRequest> request) async* {
    var result = <Result>[];
    await for (var element in request) {
      print(" element:$element");
    }

    var list = [
      "ali.com",
      "ali.com1",
      "ali.com2",
      "ali.com3",
      "ali.com4",
      "ali.com5"
    ];
    for (var feature in list) {
      var result = <Result>[];
      Future.delayed(const Duration(seconds: 1));
      print("add value:$feature");
      result.add(Result(url: feature));
      yield SearchResponse(results: result);
    }
  }
}

Future<void> main(List<String> args) async {
  final server = grpc.Server.create(services: [SearchService()], errorHandler: _onGrpcServerError);

  await server.serve(port: 50051);
  print('Server listening on port ${server.port}...');
}

void _onGrpcServerError(GrpcError error, StackTrace? trace) {
  print("grpc error :${error.toString()},full trace:${trace.toString()}");
}